﻿using Point2d.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Point2d.Graphics
{
    public class DataSupplier
    {
        XmlUtil xmlUtil = new XmlUtil();

        public DataSupplier()
        {}

        public void Load(string xmlContent)
        {
            xmlUtil.LoadXml(xmlContent);
        }

        public void Parse(GraphicsManager manager)
        {
            XmlNode root = xmlUtil.GetRoot();
            List<XmlNode> entityNodes = new List<XmlNode>();
            xmlUtil.GetChildNodesByName(root, "Entity", entityNodes);
            if (entityNodes.Count <= 0)
                return;

            foreach (XmlNode entityNode in entityNodes)
            {
                List<XmlNode> pointNodes = new List<XmlNode>();
                xmlUtil.GetChildNodesByName(entityNode, "Point", pointNodes);

                System.Drawing.Color color = System.Drawing.Color.Black;
                if (entityNode.Attributes.Count > 0)
                {
                    string colorNameFromAtt = entityNode.Attributes[0].InnerText;
                    color = System.Drawing.Color.FromName(colorNameFromAtt);
                }

                Entity entity = null;
                if (pointNodes.Count == 1)
                {
                    entity = manager._factory.Create(Entity.EntityType.ePoint, color);
                }
                else
                {
                    entity = manager._factory.Create(Entity.EntityType.eLineStrip, color);
                }

                foreach (var pointNode in pointNodes)
                {
                    string x = string.Empty;
                    string y = string.Empty;
                    for (int i = 0; i < pointNode.ChildNodes.Count; i++)
                    {
                        XmlNode childNode = pointNode.ChildNodes[i];
                        if (childNode.Name == "X")
                        {
                            x = childNode.InnerText;
                        }
                        else if (childNode.Name == "Y")
                        {
                            y = childNode.InnerText;
                        }
                    }

                    float xValue = 0.0f;
                    float yValue = 0.0f;
                    if (x != string.Empty && float.TryParse(x, out xValue) &&
                        y != string.Empty && float.TryParse(y, out yValue))
                    {
                        entity.AddPoint(xValue, yValue);
                    }
                }

                if (entity != null)
                {
                    manager.Append(entity);
                }
            }
        }
    }
}
